<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
div{width:100px; height:100px; background:red; position:absolute; top:100px; left:50px;}
</style>
<script>
	window.onload = function(){
	var oBtn1 = document.getElementById('btn1');
	var oBtn2 = document.getElementById('btn2');
	var oBtn3 = document.getElementById('btn3');
	var oBtn4 = document.getElementById('btn4');
	var oDiv = document.getElementById('div1');
	
	oBtn1.onclick = function(){
		doMove(oDiv,'left',10,800);
	}

	oBtn2.onclick = function(){
		doMove(oDiv,'left',13,50);
	}
	
	oBtn3.onclick = function(){
		doMove(oDiv,'top',13,500);
	}
	oBtn4.onclick = function(){
		doMove(oDiv,'top',13,100);
	}
}

//封装
function getStyle(obj,attr){
	return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}
//odiv 'left' -13/10  800/50
function doMove(obj,attr,dir,target,endFn){
	clearInterval(obj.timer)																				//处理重复点击加快的问题
	dir = parseInt(getStyle(obj,attr)) < target ? dir : -dir;				//判断前进方向！！
		
	obj.timer = setInterval(function(){															//记得自定义属性obj.timer
		var speed = parseInt(getStyle(obj,attr)) + dir;
		if(speed > target && dir > 0 || speed < target && dir < 0){		//向左向右条件合并
			speed = target;																						//先赋值限速，因为是表达式所以不能用 == 、===
			//clearInterval(obj.timer);	因为需要有回调函数的关系，还是到目的地清除定时器好了						//需要设置关闭定时器，如果不关闭的话，用alert(speed),到达终点还是会一直弹出800
			}
			
		obj.style[attr] = speed + 'px';															//记得px
		speed == target && clearInterval(obj.timer);								//等价于等价于if条。如果speed == target就会执行后面的清除定时器
		endFn && endFn();																						//回调函数。等价于if条
	},20)
}
</script>
</head>
<body>
<input id="btn2" type="button" value="向后">
<input id="btn1" type="button" value="向前">
<input id="btn3" type="button" value="向下">
<input id="btn4" type="button" value="向上">
<div id="div1"></div>
</body>
</html>
